<template>
  <div class="permissionauth">
    <!-- 面包屑 -->
    <Headline
      :headline1="$t('m.AccessAdmin') + '  /  '"
      :headline2="$t('m.PermissionGroupAuthorization')"
    ></Headline>
    <a-card style="width: 100%">
      <div class="lass-flex">
        <a-input-search
          :placeholder="$t('m.PleaseEnterYourSearchTerms')"
          style="width: 200px; margin-left: 15px"
          size="default"
          v-model="authset.key"
          @search="authSearch"
        />
        <div class="btn-dispos">
          <a-button
            class="btn-dispo"
            style="width: 100%; height: 32px"
            type="primary"
            @click="authbtn"
            >{{ $t("m.Add") }}</a-button
          >
        </div>
      </div>
      <a-table
        style="margin-top: 15px; overflow-x: auto"
        :rowKey="(r, i) => r.apgroupid"
        :columns="column"
        :data-source="datas"
        bordered
        :pagination="false"
      >
        <div slot="index" slot-scope="text, tag, i">
          {{ i + 1 }}
        </div>

        <div slot="tags" slot-scope="text, tags, i">
          <a-button
            class="btn"
            type="primary"
            icon="diff"
            @click="lookroles(text, tags, i)"
            >{{ $t("m.Examine") }}</a-button
          >
          <a-button
            class="btn"
            type="primary"
            icon="diff"
            @click="addroles(text, tags, i)"
            >{{ $t("m.Add") }}</a-button
          >
          <a-button
            class="btn"
            type="primary"
            icon="diff"
            @click="changed(text, tags, i)"
            >{{ $t("m.Modification") }}</a-button
          >
          <a-button
            class="btn"
            type="danger"
            icon="delete"
            @click="showModal(text, tags, i)"
            >{{ $t("m.Delete") }}</a-button
          >
        </div>
      </a-table>
      <a-pagination
        class="pages"
        show-size-changer
        :defaultPageSize="5"
        :default-current="1"
        :total="total"
        @change="authsetPages"
        :pageSizeOptions="['5', '10', '15']"
        @showSizeChange="authsetChange"
      />
    </a-card>
    <!-- 新增权限组 -->
    <Modal :modal="authfack" @modalLast="authOk" @modalhand="authhand">
     <a-form :form="form">
        <div style="width: 520px">
        <a-form-item class="box-has" :label="$t('m.PermissionGroupName')">
          <a-input 
           v-decorator="['groupName',{ rules: [{ required: true, message: '请输入权限组名称' }] },]"
          style="width: 400px" v-model="addauth.groupName" />
        </a-form-item>
        <a-form-item
          class="box-has"
          :label="$t('m.periodofvalidity')"
          validate-status="success"
        >
          <a-date-picker
            style="width: 400px"
            v-model="addauth.endDate"
            @change="endateChange"
          />
        </a-form-item>
      </div>
     </a-form>
    </Modal>
    <!-- 查看授权人员 -->
    <Modal :modal="lookfack" @modalLast="lookOk" @modalhand="lookhand">
      <div style="width: 520px; display: flex">
        <a-input-search
          :placeholder="$t('m.PleaseEnterYourSearchTerms')"
          style="width: 200px; margin-left: 15px"
          size="default"
          v-model="authset.key"
          @search="authSearch"
        />
        <div class="btn-dispos">
          <a-button
            class="btn-dispo"
            style="width: 100%; height: 32px"
            type="primary"
            @click="deleteros"
            >{{ $t("m.Delete") }}</a-button
          >
        </div>
      </div>
      <a-table
        style="margin-top: 15px; overflow-x: auto"
        :rowKey="(r, i) => r.id"
        :columns="columns"
        :data-source="looktoles"
        bordered
        :pagination="false"
        :row-selection="{
          onChange: authSelectChange,
          type: 'checkbox',
          selectedRowKeys: setsclete,
        }"
      >
        <div slot="index" slot-scope="text, tag, i">
          {{ i + 1 }}
        </div>
      </a-table>
      <a-pagination
        class="pages"
        show-size-changer
        :defaultPageSize="5"
        :default-current="1"
        :total="total"
        @change="lookPages"
        :pageSizeOptions="['5', '10', '15']"
        @showSizeChange="lookChange"
      />
    </Modal>
    <a-modal
      :title="$t('m.TheNewAuthorization')"
      width="1000px"
  :cancelText="$t('m.Cancel')"
      :okText="$t('m.Ok')"
      :visible="authvis"
      @cancel="authShow"
      @ok="authOks"
    >
      <div class="row-col">
        <a-tree-select
          v-model="value"
          show-search
          style="width: 30%"
          :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
          placeholder="Please select"
          allow-clear
          @change="authchecked"
          tree-default-expand-all
        >
          <a-tree-select-node
            v-for="item in items"
            :key="item.id"
            :cont="item"
            :value="item.custorgname"
            :title="item.custorgname"
          >
            <a-tree-select-node
              v-for="int in item.children"
              :key="int.id"
              :cont="int"
              :value="int.custorgname"
              :title="int.custorgname"
            >
              <a-tree-select-node
                v-for="ins in int.children"
                :key="ins.id"
                :cont="ins"
                :value="ins.custorgname"
                :title="ins.custorgname"
              />
            </a-tree-select-node>
          </a-tree-select-node>
        </a-tree-select>
        <a-select
          v-model="treecode.infoType"
          class="select-a"
          @change="downleSelectChange"
        >
          <a-select-option
            v-for="item in types"
            :value="item.code"
            :key="item.code"
          >
            {{ item.name }}
          </a-select-option>
        </a-select>
        <a-select
          v-model="treecode.status"
          class="select-a"
          @change="yuaneSelectChange"
        >
          <a-select-option value="-1"> 全部 </a-select-option>
          <a-select-option value="0"> 临时员工 </a-select-option>
          <a-select-option value="1">正式员工 </a-select-option>
        </a-select>
        <a-input-search
          :placeholder="$t('m.PleaseEnterYourSearchTerms')"
          style="width: 200px; margin-left: 15px"
          v-model="treecode.key"
          @search="onanthSearch"
        />
        <div class="chend">
          <a-checkbox :defaultChecked="treecode.vChild" @change="textChange">
            {{ $t("m.WhetherToDisplayChildNodes") }}
          </a-checkbox>
        </div>
      </div>
      <a-transfer
        style="margin-top: 15px"
        :locale="{ itemUnit: '项', itemsUnit: '项' }"
        :titles="['未选人员', '已选人员']"
        :data-source="authData"
        :target-keys="targetKeys"
        :disabled="disabled"
        :show-search="showSearch"
        :filter-option="
          (inputValue, item) => item.title.indexOf(inputValue) !== -1
        "
        :show-select-all="false"
        @change="onChange"
      >
        <template
          slot="children"
          slot-scope="{
            props: {
              direction,
              filteredItems,
              selectedKeys,
              disabled: listDisabled,
            },
            on: { itemSelectAll, itemSelect },
          }"
        >
          <a-table
            :row-selection="
              getRowSelection({
                disabled: listDisabled,
                selectedKeys,
                itemSelectAll,
                itemSelect,
              })
            "
            :columns="direction === 'left' ? leftColumns : rightColumns"
            :data-source="filteredItems"
            :pagination="false"
            size="small"
            :style="{ pointerEvents: listDisabled ? 'none' : null }"
            :custom-row="
              ({ key, disabled: itemDisabled }) => ({
                on: {
                  click: () => {
                    if (itemDisabled || listDisabled) return;
                    itemSelect(key, !selectedKeys.includes(key));
                  },
                },
              })
            "
          />
          <template v-if="direction === 'left'">
            <a-pagination
              class="pages"
              show-size-changer
              :defaultPageSize="5"
              :default-current="1"
              :total="transfertotal"
              @change="transferPages"
              :pageSizeOptions="['5', '10', '15']"
              @showSizeChange="transferShowpowerChange"
            />
          </template>
        </template>
      </a-transfer>
    </a-modal>
    <Delete ref="delete" :dalete="daletes" @confirm="ondelete"></Delete>
    <Delete ref="deletes" :dalete="daleterole" @confirm="edelete"></Delete>
  </div>
</template>

<script>
import Headline from "@/components/Headline";
import Modal from "@/components/common/Modal";
import Delete from "@/components/Delete";
import difference from "lodash/difference";
import {
  getGroupList,
  getSaveGroup,
  getDelGroup,
  getGroupManList,
  getdelGroupMan,
  getsetGroupMan,
} from "@/api/entrance/entranceguard";
import { getPerages, getStaff } from "@/api/perAges";
import { getdiction } from "@/api/dictionaries";
export default {
  name: "PermissionAuth",
  components: {
    Headline,
    Modal,
    Delete,
  },
  data() {
    return {
      checkNick: false,
      form: this.$form.createForm(this, { name: 'dynamic_rule' }),
      column: [
        {
          title: this.$t("m.PermissionGroupName"),
          dataIndex: "apgroupname",
        },
        {
          title: this.$t("m.periodofvalidity"),
          dataIndex: "enddate",
        },
        {
          title: this.$t("m.Operation"),
          key: "tags",
          // dataIndex: "address",
          scopedSlots: { customRender: "tags" },
        },
      ],
      datas: [],
      setsclete: [],
      authset: {
        key: "",
        page: 1,
        start: 0,
        limit: 10,
      },
      total: 0,
      authfack: {
        visible: false,
        width: "600px",
        title: this.$t("m.AddPermissionGroup"),
      },
      lookfack: {
        visible: false,
        width: "800px",
        title: this.$t("m.ViewingAuthorizedPersonnel"),
      },
      addauth: {
        groupId: 0,
        groupName: "",
        endDate: "2050-01-01",
      },
      groupId: 0,
      daletes: {
        titles: this.$t("m.DeleteThePrompt"),
        type: "exclamation-point",
        text: this.$t("m.AreYouSureToDeleteThisData"),
      },
      daleterole: {
        titles: this.$t("m.DeleteThePrompt"),
        type: "exclamation-point",
        text: this.$t("m.AreYouSureToDeleteThisData"),
      },
      looktoles: [],
      columns: [
        {
          title: this.$t("m.mergingphase"),
          dataIndex: "mergestatus",
          customRender: function (text, record, index) {
            if (text == 0) {
              return "待合并";
            } else if (text == 1) {
              return "已合并";
            }
          },
        },
        {
          title: this.$t("m.jobnumber"),
          dataIndex: "stafforstucode",
        },
        {
          title: this.$t("m.Name"),
          dataIndex: "stafforstuname",
        },
        {
          title: this.$t("m.CardNumber"),
          dataIndex: "cardno",
        },
        {
          title: this.$t("m.Sex"),
          dataIndex: "sex",
          customRender: function (text, record, index) {
            if (text == 1) {
              return "男";
            } else if (text == 2) {
              return "女";
            }
          },
        },
        {
          title: this.$t("m.AffiliatedUnit"),
          dataIndex: "orgname",
        },
        {
          title: this.$t("m.creationTime"),
          dataIndex: "createdate",
        },
      ],
      lookfrom: {
        groupId: 0,
        key: "",
        page: 1,
        start: 0,
        limit: 10,
      },
      totals: 0,
      deleteroles: {
        ids: "",
        groupId: 0,
      },
      authvis: false,
      value: "",
      formunitdata: {
        orgType: 1,
        key: "",
      },
      items: [],
      authData: [],
      targetKeys: [],
      disabled: false,
      showSearch: false,
      treecode: {
        ymOrgTreeCode: "",
        infoType: "1",
        status: "-1",
        vChild: true,
        property: -1,
        page: 1,
        start: 0,
        limit: 50,
      },
      leftColumns: [
        { title: this.$t("m.jobnumber"), dataIndex: "stafforstucode" },
        { title: this.$t("m.Name"), dataIndex: "stafforstuname" },
        { title: this.$t("m.Sex"), dataIndex: "sex" },
        { title: this.$t("m.AffiliatedUnit"), dataIndex: "orgname" },
      ],
      rightColumns: [
        { title: this.$t("m.Name"), dataIndex: "stafforstuname" },
        { title: this.$t("m.AffiliatedUnit"), dataIndex: "orgname" },
      ],
      transfertotal: 0,
      anthIdfrom: {
        groupId: 0,
        infoIds: "",
      },
      dictionfrom: {
        groupcode: "SYS0000019",
        insertall: "",
        where: "",
        page: 1,
        start: 0,
        limit: 25,
      },
      types: [],
      typelists: [],
    };
  },
  created() {
    this._getGroupList();
    this._getPerages();
    this._getdiction();
  },
  methods: {
    //获取字典
    _getdiction() {
      getdiction({ params: this.dictionfrom }).then((res) => {
        console.log(res);
        this.types = res.data.data;
      });
    },

    _getGroupList() {
      getGroupList({ params: this.authset }).then((res) => {
        console.log(res);
        this.total = res.data.total;
        this.datas = res.data.data;
      });
    },
    //请求授权数据
    _getPerages() {
      getPerages({ params: this.formunitdata })
        .then((res) => {
          console.log(res);
          if (res.data) {
            this.items = res.data;
            this.$message.success("获取单位数据成功");
          }
        })
        .catch((err) => {
          this.$message.error("获取单位数据失败");
        });
    },
    // Create搜索
    authSearch() {
      this._getGroupList();
    },
    //新增
    authbtn() {
      this.authfack.visible = true;
    },
    _getSaveGroup() {
      getSaveGroup(this.addauth)
        .then((res) => {
          const msg = res.data.msg;
          if (res.data.success) {
            this.$message.success(msg);
            this._getGroupList();
          } else {
            this.$message.srror(msg);
          }
        })
        .catch((err) => {
          console.log(err);
        });
      this.addauth.groupName = "";
      this.addauth.endDate = "";
      this.addauth.groupId = 0;
    },
    //新增确认
    authOk() {
      this.form.validateFields(err => {
        if (!err) {
          console.info('success');
        }
      });

     if(this.addauth.groupName != ""){
        this._getSaveGroup();
      this.authfack.visible = false;
     }
    },
    //取消
    authhand() {
      this.authfack.visible = false;
    },
    //选中列表
    authSelectChange(select, text) {
      console.log(select, text);
      this.setsclete = select;
      this.deleteroles.ids = select.join(",");
    },
    //修改
    changed(text, tags, i) {
      this.authfack.visible = true;
      console.log(text, tags, i);
      this.addauth.groupId = tags.apgroupid;
      this.addauth.groupName = tags.apgroupname;
    },
    //删除
    showModal(text, tags, i) {
      this.$refs.delete.visible = true;
      this.groupId = tags.apgroupid;
    },
    //删除确定
    ondelete() {
      getDelGroup({ groupId: this.groupId })
        .then((res) => {
          const msg = res.data.msg;
          if (res.data.success) {
            this.$message.success(msg);
            this._getGroupList();
          } else {
            this.$message.error(msg);
          }
        })
        .catch((err) => {
          console.log(err);
        });
      this.$refs.delete.visible = false;
    },
    //新增人员
    addroles(text, tags, i) {
      this.authvis = true;
      this.anthIdfrom.groupId = tags.apgroupid;
      this._chexd();
    },
    _getGroupManList() {
      getGroupManList({ params: this.lookfrom }).then((res) => {
        console.log(res);
        this.totals = res.data.total;
        this.looktoles = res.data.data;
        this.lookfack.visible = true;
      });
    },
    //查看
    lookroles(text, tags, i) {
      this.lookfrom.groupId = tags.apgroupid;
      this.deleteroles.groupId = tags.apgroupid;

      this._getGroupManList();
    },
    //删除
    deleteros() {
      if (this.setsclete.length > 0) {
        this.$refs.deletes.visible = true;
      } else {
        this.$message.error("请选择要删除的数据");
      }
    },
    //删除确定
    edelete() {
      getdelGroupMan(this.deleteroles)
        .then((res) => {
          const msg = res.data.msg;
          if (res.data.success) {
            this.$message.success(msg);
            this._getGroupManList();
          } else {
            this.$message.srror(msg);
          }
        })
        .catch((err) => {
          console.log(err);
        });
      this.$refs.deletes.visible = false;
    },
    lookOk() {
      this.lookfack.visible = false;
      this.deleteroles.ids = "";
      this.setsclete = [];
    },
    lookhand() {
      this.lookfack.visible = false;
      this.deleteroles.ids = "";
      this.setsclete = [];
    },
    //穿梭框弹窗
    authOks() {
      getsetGroupMan(this.anthIdfrom)
        .then((res) => {
          const msg = res.data.msg;
          if (res.data.success) {
            this.$message.success(msg);
          } else {
            this.$message.error(msg);
          }
        })
        .catch((err) => {
          console.log(err);
        });
      this.authvis = false;
      this.targetKeys = [];
      this.anthIdfrom.infoIds = "";
    },
    authShow() {
      this.authvis = false;
      this.targetKeys = [];
      this.anthIdfrom.infoIds = "";
    },
    //选中触发
    authchecked(value, label, extra) {
      if (extra.triggerNode) {
        //获取当前选中的对象信息
        const cont = extra.triggerNode.$attrs.cont;
        console.log(cont);
        this.treecode.ymOrgTreeCode = cont.ymorgtreecode;
        this._getStaff();
      }
    },
    // 默认展示数据
    _chexd() {
      //默认选择第一条数据
      const item = this.items[0];
      this.treecode.ymOrgTreeCode = item.ymorgtreecode;
      this.value = item.custorgname;
      this._getStaff();
    },
    onanthSearch() {
      this._getStaff();
    },
    textChange() {
      this.treecode.vChild = !this.treecode.vChild;
      this._getStaff();
    },
    downleSelectChange() {
      this._getStaff();
    },
    yuaneSelectChange() {
      this._getStaff();
    },
    //请求表单数据
    _getStaff() {
      getStaff({ params: this.treecode }).then((res) => {
        this.transfertotal = res.data.total;
        this.authData = res.data.data.map((item) => {
          return {
            title: item.orgname,
            key: item.id + "",
            disabled: false,
            stafforstucode: item.stafforstucode,
            stafforstuname: item.stafforstuname,
            sex: item.sex == "1" ? "男" : "女",
            orgname: item.orgname,
          };
        });
      });
    },
    //穿梭框方法
    triggerShowSearch(showSearch) {
      this.showSearch = showSearch;
      console.log(showSearch);
    },
    onChange(nextTargetKeys, e, a) {
      this.targetKeys = nextTargetKeys;
      console.log(nextTargetKeys, a);
      this.anthIdfrom.infoIds = nextTargetKeys.join(",");
    },
    triggerDisable(disabled) {
      this.disabled = disabled;
    },
    getRowSelection({ disabled, selectedKeys, itemSelectAll, itemSelect }) {
      return {
        getCheckboxProps: (item) => ({
          props: { disabled: disabled || item.disabled },
        }),
        onSelectAll(selected, selectedRows) {
          const treeSelectedKeys = selectedRows
            .filter((item) => !item.disabled)
            .map(({ key }) => key);
          const diffKeys = selected
            ? difference(treeSelectedKeys, selectedKeys)
            : difference(selectedKeys, treeSelectedKeys);
          itemSelectAll(diffKeys, selected);
        },
        onSelect({ key }, selected) {
          console.log(key);
          itemSelect(key, selected);
        },
        selectedRowKeys: selectedKeys,
      };
    },
    //时间处理
    endateChange(date, dateString) {
      this.addauth.endDate = dateString;
    },
    //分页
    authsetPages(page, limit) {
      console.log(page, limit);
      this.authset.page = page;
      this.authset.limit = limit;
      this.authset.start = (page - 1) * limit;
      this._getGroupList();
    },
    authsetChange(page, pageSize) {
      this.authset.page = page;
      this.authset.limit = pageSize;
      this.authset.start = (page - 1) * pageSize;
      this._getGroupList();
    },
    lookPages(page, limit) {
      console.log(page, limit);
      this.lookfrom.page = page;
      this.lookfrom.limit = limit;
      this.lookfrom.start = (page - 1) * limit;
      this._getGroupManList();
    },
    lookChange(page, pageSize) {
      this.lookfrom.page = page;
      this.lookfrom.limit = pageSize;
      this.lookfrom.start = (page - 1) * pageSize;
      this._getGroupManList();
    },

    transferPages(page, limit) {
      console.log(page, limit);
      this.treecode.page = page;
      this.treecode.limit = limit;
      this.treecode.start = (page - 1) * limit;
      this._getStaff();
    },
    transferShowpowerChange(page, pageSize) {
      this.treecode.page = page;
      this.treecode.limit = pageSize;
      this.treecode.start = (page - 1) * pageSize;
      this._getStaff();
    },
  },
};
</script>

<style scoped lang="scss">
.lass-flex {
  display: flex;
  align-items: center;
}
.btn-dispos {
  margin-left: 15px;
}
.box-has {
  display: flex;
  justify-content: flex-end;
}
.row-col {
  display: flex;
  align-items: center;
}
.select-a {
  margin-left: 15px;
  width: 100px;
}
.chend {
  margin-left: 15px;
}
.btn{
  margin-left: 15px;
}
</style>